package com.library.controller;/*
 *@author lzg
 *@data 2020/11/21
 */

import com.library.entity.Book;
import com.library.entity.BorrowRecode;
import com.library.entity.Reader;
import com.library.service.BookService;
import com.library.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


/**
 * 加载图书数据
 */
@WebServlet("/book")
public class BookServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method==null){
            method = "findAll";
        }
        switch (method){
            case "findAll":
                String page = req.getParameter("page");
                int pageIndex = Integer.parseInt(page);
                List<Book> bookList = bookService.findAll(pageIndex);
                int limitNum = 6;//每页多少行
                //每页数量
                req.setAttribute("dataPrePage", limitNum);
                //当前页数
                req.setAttribute("currentPage", pageIndex);
                //总页数
                req.setAttribute("pages", bookService.getPageSize(limitNum));
                //设置将booklist数据传给前段
                req.setAttribute("list", bookList);
                req.getRequestDispatcher("index.jsp").forward(req,resp);
                break;
            case "addBorrow":
                //根据前端传入的bookid判断借阅流程
                String bookIdStr = req.getParameter("bookid");
                Integer bookId = Integer.parseInt(bookIdStr);
                HttpSession session = req.getSession();
                Reader reader = (Reader)session.getAttribute("reader");
                Integer readerId = reader.getId();
                bookService.addBorrow(bookId,readerId);
                //跳转到借阅的记录页面，展示什么内容？关联几个表？获取数据后存储到一个对象中

                List<BorrowRecode> borrowRecodesList = bookService.findAllBorrowRecodeByReaderId(readerId);
                req.setAttribute("list", borrowRecodesList);
                req.getRequestDispatcher("borrow.jsp").forward(req,resp);
                break;
        }
    }
}
